// packageA/pages/equipmentCheckAdd/equipmentCheckAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{
      isWork: '1',
      isClean: '1'
    },
    //库存信息
    repertoryInfo:null,
    //提交按钮禁用
    disabled:false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //搜索词
    valueSearch:'',
    //开始时间选择框
    showStartTime:false,
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2: null,  
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加检测传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      //获取库存信息
      if(paramObj.repertoryId){
        //获取库存信息
        this.getRepertory();
      }
    }
  },

  //提交表单
  confirmForm(e){
    this.setData({
      disabled:true
    })
 
    let obj=e.detail.value;
    let editInfo=this.data.editInfo;
    let rInfo=this.data.repertoryInfo;

    //开始和结束时间必填
    if(!editInfo.startDate){
      Toast.fail('请选择开始时间');
      return;
    }
    if(!editInfo.endDate){
      Toast.fail('请选择结束时间');
      return;
    }

    //时间大小
    if(editInfo.startDate>editInfo.endDate){
      Toast.fail('结束时间不能早于开始时间');
      return;
    }

    //人员必填
    if(!editInfo.testMan){
      Toast.fail('请选择检测人员');
      return;
    }
    
    //工作时长为数字
    let runTime=obj.runTime.trim();
    if(runTime){
      if((/^([0-9][0-9]*)+(.[0-9]{1,2})?$/).test(runTime)){
      }else{
        Toast.fail('工作时长为数字');
        return;
      } 
    }

    let param={
      appId: [app.globalData.myAppId],
      testRecord:[{
        id: null,
        startDate: editInfo.startDate2,
        endDate: editInfo.endDate2,
        testMan: editInfo.testMan,
        isWork: Number(editInfo.isWork),
        isClean: Number(editInfo.isClean),
        facade: obj.facade.trim(),
        runTime: runTime,
        remark: obj.remark.trim(),
        date: [editInfo.startDate,editInfo.endDate]
      }]
    }

    //合并对象
    Object.assign(param,rInfo); 

    //console.log(param);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.checkItem(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取库存信息
  getRepertory(){
    let param = {
      isAuth: false,
      className: 'repertory',
      data: {
        id: this.data.paramObj.repertoryId,
        type: 1,
        selectFields: ["id","equipmentNo","imei","type", "num","category", "createDate", "name", "spec","unit","depot","relationOrderNo","leaseRecord","ioStorageDetail","performance","remarks","checkRecord","maintain","checkRemarks","orderObj","service","keepAccounts","dataAuthority","accountingPrice","state"]
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('库存信息');
        console.log(result);

        this.setData({
          repertoryInfo: result
        })
      }
    }).catch((error) => {
    })
  },
  
  //用户输入时清除错误提示
  clearMessage(e) {
    let obj = {};
    obj['disabled'] = false;
    this.setData(obj);
  },
 
  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示开始时间
  onShowStartTime(){
    if(!this.data.readOnly){
      this.setData({
        showStartTime: true
      })
    }  
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    let start='editInfo.startDate';
    let start2='editInfo.startDate2';
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      [start]:util.timeFormat(e.detail),
      [start2]:new Date(e.detail),
      disabled:false
    })
    this.onCloseStartTime();
  },

  //显示结束时间
  onShowEndTime(){
    if(!this.data.readOnly){
      this.setData({
        showEndTime: true
      })
    }  
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    let end='editInfo.endDate';
    let end2='editInfo.endDate2';
    this.setData({
      currentEnd: e.detail,
      [end]:util.timeFormat(e.detail),
      [end2]:new Date(e.detail),
      disabled:false
    })
    this.onCloseEndTime();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })
    
    let dataset=e.target.dataset;
    let field=dataset.field;   
    
    this.setData({
      showSelect: true,
      selectField: field
    })

    //人员
    if(field=='user'){
      this.setData({
        selectTitle: '检测人员',
        showSelectSearch: true
      })
      this.getUserList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    this.setData({
      valueSearch: '',
      disabled: false
    })  

    //人员
    if(selectField=='user'){
      obj='editInfo.testMan';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }
    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;    
    
    this.setData({
      valueSearch: e.detail,
      selectList: []
    }) 

    //人员
    if(selectField=='user'){
      this.getUserList();
    }
  },

  //查询人员
  getUserList(){
    let param = {
      isAuth: true,
      className: 'user',
      data: {
        depart: 1,
        searchAll: true,
        selectFields: ['id','userName']
      }
    }
   
    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.userName,
            id:item.id,
            obj:{
              id:item.id,
              name:item.userName
            }
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //工作正常单选
  onChangeWork(event) {
    let isWork='editInfo.isWork';
    this.setData({
      [isWork]: event.detail,
    })
  },

  //清洁效果单选
  onChangeClean(event) {
    let isClean='editInfo.isClean';
    this.setData({
      [isClean]: event.detail,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})